package com.pi.shisan.service.config;

import com.pi.shisan.service.audio.AudioLevelManager;
import com.pi.shisan.service.schedule.ScheduleCreater;
import com.pi.shisan.service.service.VolumeSettingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.util.Properties;
import java.util.function.Consumer;

@Slf4j
@Configuration
public class CommonConfig{

    @Bean
    public AudioLevelManager audioLevelManager() {
        return new AudioLevelManager();
    }

    @Bean(initMethod = "createAndStartDefault")
    public ScheduleCreater scheduleCreater() {
        return new ScheduleCreater();
    }

    @Bean
    public HttpClient httpClient() {
        return new ListenerHttpClient();
    }

    @Bean
    public AnnotationScannerConfigurer annotationScannerConfigurer(){
        return new AnnotationScannerConfigurer();
    }

    @Bean
    public Consumer<Integer> playBeforeVolume(@Autowired VolumeSettingService volumeSettingService) {
        return v-> {
            if (v == null || v <= 0) {
                try {
                    volumeSettingService.resetVolume();
                } catch (Exception e) {
                    log.error("重置系统音量失败：",e);
                }
                return;
            }
            try {
                volumeSettingService.justSetVolume(v);
            } catch (Exception e) {
                log.error("设置系统音量失败：",e);
            }
        };
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() throws Exception{
        Properties props = new Properties();
        props.put("org.quartz.scheduler.instanceName","schedule-worker-");
        props.put("org.quartz.threadPool.threadCount","1");
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
        schedulerFactory.initialize(props);
        schedulerFactoryBean.setSchedulerFactory(schedulerFactory);
        return schedulerFactoryBean;
    }
}
